<?php

namespace model;

use model\config;

class visits
{
    /**
     * 写入访问量信息
     * id
     * date   datetime
     * visits  int
     */
    public static function insertData()
    {
        $time = config::getCache('visitstime');
        $num = 1;

        if (config::getCache('visitscache') == 1) {
            $num = config::getCache('visitsnum') ?? 1;
            $getCache = intval(GetCxuuCache('visits_inc')) ?? 0;
            SetCxuuCache('visits_inc', $getCache += 1, $time);
            if ($getCache < $num)
                return;
            else
                $num  = $getCache;
        }

        $pdo = \libs\pdo::Init();
        $prefix = $pdo->GetConfig();
        $fix = $prefix['prefix'];
        $date = date('Y-m-d', time());
        $result = $pdo->Submit("UPDATE {$fix}visits SET visits = visits+{$num} WHERE DATEDIFF(date,NOW()) = 0");
        SetCxuuCache('visits_inc', 0, $time);
        if (empty($result))
            $pdo->Submit("INSERT INTO `{$fix}visits` (`id`, `date`, `visits`) VALUES (NULL, '{$date}', '{$num}')");
    }

    /**
     * 获取访问量信息 
     * id
     * date   datetime
     * visits  int
     */
    static public function findData()
    {
        $time = config::getCache('visitsshowtime') ?? 600;
        $db = \libs\db::Init('visits');
        $dataToday = $db->where('DATEDIFF(date,NOW()) = 0')->cache($time)->select();
        $yesterdaySql = $db->where('DATEDIFF(date,NOW()) = -1')->cache($time)->select();
        $count = $db->Field('SUM(visits) AS sum,MAX(visits) AS max')->cache($time)->find();
        return [
            'today' => $dataToday[0]['visits'] ?? 0,
            'yesterday' =>  $yesterdaySql[0]['visits'] ?? 0,
            'sum' => $count['sum'],
            'max' => $count['max'],
        ];
    }
}
